//
//  TCAudienceUSERViewController.swift
//  onemeetingmac
//
//  Created by 张衡 on 2020/7/2.
//  Copyright © 2020 onemeeting. All rights reserved.
//

import Foundation

class TCAudienceUSERViewController: NSViewController {
    
    var dataList:[AdcInfo] = []
    var isJoin:Bool = Td.sh().isJoin
    var upMenu:NSMenu!
    var selectUserInfo:AdcInfo!
    
    
    override func loadView() {
        let view = NSView.init(frame: NSMakeRect(0, 0, kTRTCUserWidth, kTRTCWinHeight))
        view.wantsLayer = true
        view.layer?.backgroundColor = NSColor.white.cgColor
        self.view = view
    }
    
    override func viewDidLoad() {
        super.viewDidLoad()
        self.setupUI()
    }
    
    override func viewWillAppear() {
        super.viewWillAppear()
        NotificationCenter.default.addObserver(self, selector: #selector(userStatuChange(not:)), name: MTUserStateNotification, object: nil)
        NotificationCenter.default.addObserver(self, selector: #selector(allDownHandUp(not:)), name: MTADownHandUpNotification, object: nil)
        NotificationCenter.default.addObserver(self, selector: #selector(addUser(not:)), name: MTAddAdcNotification, object: nil)
        NotificationCenter.default.addObserver(self, selector: #selector(deleteUser(not:)), name: MTDeleteAdcNotification, object: nil)
    }
    override func viewDidAppear() {
        super.viewDidAppear()
        self.reloadDataAndlist()
    }
    
    func reloadDataAndlist() {
        var dataList = Td.sh().usr.adcs
        if Td.sh().lc.isAdc == true {
            var info = AdcInfo.init()
            info.userId = Td.sh().lc.userId
            info.nickName = Td.sh().lc.nickName
            info.isHandUp = Td.sh().lc.isHandUp
            dataList.insert(info, at: 0)
        }
        self.dataList = dataList
        self.tabView.kreloadData()
    }
    
    func setupUI()  {
        self.view.layer?.backgroundColor = color_random_rgba().cgColor
        
        self.view.addSubview(scrollView)
        scrollView.snp.makeConstraints { (make) in
            make.left.right.equalToSuperview()
            make.top.equalTo(0)
            make.bottom.equalTo(0)
        }
    }
    
    lazy var scrollView: NSScrollView = {
        let view = NSScrollView()
        view.documentView = self.tabView
        view.hasVerticalScroller = false
        view.hasHorizontalScroller = false
        view.autohidesScrollers = true
        view.drawsBackground = false
        //view.wantsLayer = true
        //view.layer?.backgroundColor = color_gray(240).cgColor
        return view
    }()
    
    lazy var tabView: NSTableView  = {
        let tab = NSTableView()
        tab.wantsLayer = true
        tab.backgroundColor = color_dark
        tab.delegate = self
        tab.dataSource = self
        //tab.gridStyleMask = NSTableView.GridLineStyle.dashedHorizontalGridLineMask
        tab.gridColor = color_gray(240)
        tab.selectionHighlightStyle = .none
        //tab.usesAlternatingRowBackgroundColors = true

        let column = NSTableColumn.init(identifier: NSUserInterfaceItemIdentifier.init("column"))
        tab.addTableColumn(column)
        //column.width = self.view.frame.size.width
        tab.headerView = nil
        return tab
    }()
    
}

extension TCAudienceUSERViewController:NSTableViewDelegate,NSTableViewDataSource {
    func numberOfRows(in tableView: NSTableView) -> Int {
        return self.dataList.count
    }
    
    func tableView(_ tableView: NSTableView, viewFor tableColumn: NSTableColumn?, row: Int) -> NSView? {
        var cell = tableView.makeView(withIdentifier: NSUserInterfaceItemIdentifier.init(mt_cell_default), owner: self) as? TCAudienceUSERCell
        if let userInfo = self.dataList[safe:row]  {
            if cell == nil {
                cell = TCAudienceUSERCell.init(adcInfo: userInfo,isJoin:self.isJoin,identifier: mt_cell_default)
                cell?.highAction = { (uCell,senber) in
                    self.hightAction(cell: uCell as! TCAudienceUSERCell, senber: senber, row: row)
                }
            }
            cell?.upmicBg.isHidden = !userInfo.isLoading
            cell?.avatarImg.text = userInfo.nickName
            cell?.title.stringValue = userInfo.nickName
            cell?.identityLab.stringValue = self.getIdentity(userInfo.userId!)
            return cell
        }
        return nil
    }
    
    func tableView(_ tableView: NSTableView, heightOfRow row: Int) -> CGFloat {
        return 46
    }
    
    func tableView(_ tableView: NSTableView, shouldSelectRow row: Int) -> Bool {
        let rowView = tableView.rowView(atRow: row, makeIfNecessary: false)
        rowView?.isEmphasized = true
        rowView?.isGroupRowStyle = false
        rowView?.isSelected = false
        rowView?.isFloating = false
        rowView?.isNextRowSelected  = false
        rowView?.isPreviousRowSelected = false
        rowView?.isTargetForDropOperation = false
        return true
    }
    
    func tableViewSelectionDidChange(_ notification: Notification) {
        let tab = notification.object as? NSTableView
        print(tab as Any)
    }
    
    
    func hightAction(cell:TCAudienceUSERCell,senber:ZHButton,row:Int) {
        let uInfo = self.dataList[row]
        self.selectUserInfo = uInfo
        if senber.zh_title == TITLE_MORE {
            self.moreAction(sender: senber, info: uInfo, isjoin: self.isJoin)
        }else {
            self.textAction(string: senber.zh_title)
        }
    }
    
    
    func showChangeName(senber:NSView?) {
        let dialogVc = DialogViewController()
        let popover = AsPopover.create(controller: dialogVc)
        popover.show(senber!, preferredEdge: NSRectEdge.minX)
        popover.perform_detach()
        
    }
    
    func getIdentity(_ t:String) -> String {
        if t.isHostId() && t.isCurret() {
            return "(主持人,我)"
        }else if t.isHostId() {
            return "(主持人)"
        }else if t.isCurret() {
            return "(我)"
        }
        return ""
    }
    
    func moreAction(sender:ZHButton,info:AdcInfo,isjoin:Bool) {
        let menu = NSMenu.init()
        menu.isDark = true
        let titles = TCAudienceUSERViewController.moreTitles(info: info, isjoin: isjoin)
        self.createItems(names: titles).forEach { (item) in
            menu.addItem(item)
        }
        menu.needsUpdate()
        let p = NSPoint(x: 0, y: sender.frame.origin.y+sender.frame.height)
        self.upMenu = menu
        self.upMenu!.popUp(positioning: nil, at: p, in: sender)
    }
    
    class func moreTitles(info:AdcInfo,isjoin:Bool) -> [String] {
        var titles = TCAudienceUSERViewController.menuItemTitles(info: info, isjoin: isjoin)
        titles.remove(at: 0)
        return titles
    }
    
    class func bacisTitls(info:AdcInfo,isjoin:Bool) -> [String] {
        var names:[String] = []
        let titles = TCAudienceUSERViewController.menuItemTitles(info: info, isjoin: isjoin)
        if titles.count > 2 {
            names.append(TITLE_MORE)
            names.append(titles[0])
        }else {
            names = titles
        }
        return names
    }
    
    class func menuItemTitles(info:AdcInfo,isjoin:Bool) -> [String] {
        var highs:[String] = []
        if isjoin == false {
            highs.append(TITLE_MICINVITE)
            if info.isHandUp == true {
                highs.append(TITLE_HANDDOWN)
            }
            highs.append(TITLE_REMOVE)
        }else {
            if info.userId?.isCurret() == true {
                highs.append(TITLE_MFNAME)
            }
        }
        return highs
    }
    
    func createItems(names:[String]) -> [NSMenuItem] {
        var item:[NSMenuItem] = []
        for (index,value) in names.enumerated() {
            let menu = NSMenuItem.init(title: value, action: #selector(menuItemAction(sender:)), keyEquivalent: "")
            menu.tag = index
            menu.target = self
            menu.isEnabled = true
            item.append(menu)
            
            item.append(NSMenuItem.separator())
        }
        return item
    }
    
    @objc func menuItemAction(sender:NSMenuItem) {
        self.textAction(string: sender.title)
    }
    
    func textAction(string:String) {
        let uInfo = self.selectUserInfo!
        switch string {
        case TITLE_MFNAME:
            self.showChangeName(senber: self.tabView)
        case TITLE_REMOVE:
            self.removeAction(info: uInfo)
        case TITLE_HANDDOWN:
            self.downHand(userId: uInfo.userId!)
        case TITLE_MICINVITE:
            self.inviteUpAction(info: uInfo)
        case TITLE_MORE:
            break
        default:
            break
        }
    }
    
    
    func removeAction(info:AdcInfo) {
        DispatchQueue.main.asyncAfter(deadline: DispatchTime.now()) {
            let controller =  KlViewController.init(title: "移出会议", massage: "是否移出“\(info.nickName)”用户", buttomTitles: ["确定","取消"], indexBlock: { (index, control) in
                if index == 0 {
                    IMcmd.shared.kick(userId: info.userId!)
                }
            }, navBlock: nil)
            let window = NSWindow.init(contentViewController: controller)
            window.makeKeyAndOrderFront(nil)
        }
    }
    
    func inviteUpAction(info:AdcInfo) {
        DispatchQueue.main.asyncAfter(deadline: DispatchTime.now()) {
            let controller =  KlViewController.init(title: "邀请上麦", massage: "确认邀请 \(info.nickName) 上麦", buttomTitles: ["确定","取消"], indexBlock: { (index, control) in
                 if index == 0 {
                    IMcmd.shared.setRole(isAnchor: true,confirm: 1,userId: info.userId!)
                 }
             }, navBlock: nil)
            let window = NSWindow.init(contentViewController: controller)
            window.makeKeyAndOrderFront(nil)
        }
    }
    
    func downHand(userId:String) {
        IMcmd.shared.downUserHand(userId: userId)
    }
    
}

extension TCAudienceUSERViewController {
    
    @objc func allDownHandUp(not:Notification) {
        if not.object as? String == ReloadNotification {
            self.reloadDataAndlist()
            return
        }
    }
    
    @objc func userStatuChange(not:Notification) {
        guard let mode = not.object as? UserMode else {
            return
        }
        
        let indx = self.dataList.firstIndex { (info) -> Bool in
            let userid = mode.userId ?? Td.sh().lc.userId!
            return info.userId==userid
        }
        guard let index = indx else { return  }
        if let isHandUp = mode.isHandUp{
            self.dataList[index].isHandUp = isHandUp
            self.reloadDataAndlist()
        }
        if let name = mode.nickName {
            self.dataList[index].nickName = name
            self.reloadDataAndlist()
        }
        
    }
    
    @objc func addUser(not:Notification) {
        guard let mode = not.object as? AdcInfo else {
            return
        }
        print("mode=\(mode)")
        self.reloadDataAndlist()
    }
    
    @objc func deleteUser(not:Notification) {
        guard let mode = not.object as? String else {
            return
        }
        print("mode=\(mode)")
        self.reloadDataAndlist()
    }
}
